package com.hy.demo.learn.开发支持类库.ThreadLocal类;

/**
 * <p>
 * ThreadLocal类
 * </p>
 *
 * @author cjl
 * @version 1.0
 * @since 2020-08-28 09:55
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {

        new Thread(() -> {
            Message message = new Message();
            message.setInfo("第一个线程 hello word");
            Channel.setMessage(message);
            Channel.send();
        }, "第一个线程").start();

        new Thread(() -> {
            Message message = new Message();
            message.setInfo("第二个线程 hello word");
            Channel.setMessage(message);
            Channel.send();
        }, "第二个线程").start();

        new Thread(() -> {
            Message message = new Message();
            message.setInfo("第三个线程 hello word");
            Channel.setMessage(message);
            Channel.send();
        }, "第三个线程").start();

    }
}

class Message {
    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

class Channel {

    // ThreadLocal 解决多线程开发中数据同步问题
    private static final ThreadLocal<Message> threadLocal = new ThreadLocal<>();

    private Channel() {
    }

    public static void setMessage(Message ms) {
        threadLocal.set(ms);
    }

    public static void send() {
        System.out.println(Thread.currentThread().getName() + "发送消息----" + threadLocal.get().getInfo());
    }
}
